package com.ruoyi.mtg.utils;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.mtg.domain.CardData;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public abstract class MtgUtil {

    /**
     * www.iyingdi.com 营地查询卡牌中文信息
     *
     * @param cardname 英文卡名
     * @return
     */
    public static CardData queryCardFromIyingdi(String cardname) {
        Map<String, Object> params = new HashMap<>();
        params.put("name", cardname);   // 模糊查询
        params.put("statistic", "total");
        params.put("token", "");
        params.put("page", 0);
        params.put("size", 30);
        params.put("collect", 0);
        String res = HttpUtil.post("https://www.iyingdi.com/magic/card/search/vertical", params);
        log.debug("{}", res);
        JSONObject jo = JSON.parseObject(res);
        Boolean success = jo.getBoolean("success");
        log.debug("http query: success = {}, name = {}", success, cardname);
        if (!success) {
            return null;
        }
        JSONObject data = jo.getJSONObject("data");
        int total = data.getInteger("total");
        if (total <= 0) {
            return null;
        }
        JSONArray cards = data.getJSONArray("cards");
        if (null == cards || cards.size() == 0) {
            return null;
        }
        JSONObject card = cards.stream()
                .map(o -> (JSONObject) o)
                .filter(o -> cardname.equalsIgnoreCase(o.getString("ename")))
                .findFirst()
                .orElse(null);
        if (null == card) {
            return null;
        }
        String cname = card.getString("cname");
//        String clazz = card.getString("clazz");
        String mainType = card.getString("mainType");
        String rule = card.getString("rule");
        return new CardData().setNameCn(cname).setTypeCn(mainType).setTextCn(rule);
    }
}
